package com.promise.jokerdream.ui.settings

import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight
import com.promise.jokerdream.database.entity.ExperienceGameConfigEntity
import com.promise.jokerdream.config.game.ExperiencePriorityType
import com.promise.jokerdream.model.misty.MistyMapping
import com.promise.jokerdream.ui.components.SettingCard
import com.promise.jokerdream.ui.components.CheckboxOptionRow
import com.promise.jokerdream.ui.components.RoundCheckbox
import com.promise.jokerdream.ui.components.MultiSelectHashtagBottomSheet
import com.promise.jokerdream.ui.components.SelectionRow
import com.promise.jokerdream.ui.theme.AppSpacing
import com.promise.jokerdream.ui.theme.AppFontSizes

/**
 * 历练设置卡片
 */
@Composable
fun ExperienceSettingCard(
    config: ExperienceGameConfigEntity,
    onExperienceChange: (Boolean) -> Unit,
    onPriorityTypeChange: (ExperiencePriorityType) -> Unit,
    onCustomOrderChange: (List<Int>) -> Unit,
    onVitalityPotionChange: (Boolean) -> Unit,
    modifier: Modifier = Modifier,
    onExecuteClick: (() -> Unit)? = null
) {
    SettingCard(
        title = "历练",
        description = "",
        checked = config.enabledSetting,
        onCheckedChange = onExperienceChange,
        modifier = modifier,
        onExecuteClick = onExecuteClick,
        content = {
            if (config.enabledSetting) {
                Column(
                    modifier = Modifier.fillMaxWidth()
                ) {
                    // 历练优先级选择区域
                    // 转换 priorityType: String -> ExperiencePriorityType
                    val priorityType = try {
                        ExperiencePriorityType.valueOf(config.priorityType)
                    } catch (e: Exception) {
                        ExperiencePriorityType.EXPERIENCE
                    }
                    // 转换 customOrder: String -> List<Int>
                    val customOrder = if (config.customOrder.isEmpty()) {
                        emptyList()
                    } else {
                        config.customOrder.split(",").mapNotNull { it.trim().toIntOrNull() }
                    }
                    ExperiencePriorityArea(
                        priorityType = priorityType,
                        customOrder = customOrder,
                        onPriorityTypeChange = onPriorityTypeChange,
                        onCustomOrderChange = onCustomOrderChange
                    )
                    
                    Spacer(modifier = Modifier.height(AppSpacing.componentMedium))
                    
                    // 活力药水开关
                    CheckboxOptionRow(
                        title = "使用活力药水",
                        checked = config.useVitalityPotion,
                        onCheckedChange = onVitalityPotionChange
                    )
                }
            }
        }
    )
}

/**
 * 历练优先级选择区域
 */
@Composable
private fun ExperiencePriorityArea(
    priorityType: ExperiencePriorityType,
    customOrder: List<Int>,
    onPriorityTypeChange: (ExperiencePriorityType) -> Unit,
    onCustomOrderChange: (List<Int>) -> Unit
) {
    Column {
        // 标题行
        Text(
            text = "历练策略:",
            fontSize = AppFontSizes.body,
            color = MaterialTheme.colorScheme.onSurface
        )
        
        Spacer(modifier = Modifier.height(AppSpacing.componentSmall))
        
        // 经验优先和天赋丹优先 - 保持原来的左右布局
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(vertical = AppSpacing.componentSmall),
            horizontalArrangement = Arrangement.SpaceBetween,
            verticalAlignment = Alignment.CenterVertically
        ) {
            // 经验优先选项
            CheckboxOptionRow(
                title = "经验优先",
                checked = priorityType == ExperiencePriorityType.EXPERIENCE,
                onCheckedChange = { onPriorityTypeChange(ExperiencePriorityType.EXPERIENCE) },
                modifier = Modifier.weight(1f)
            )

            // 天赋丹优先选项
            CheckboxOptionRow(
                title = "天赋丹优先",
                checked = priorityType == ExperiencePriorityType.VITALITY_POTION,
                onCheckedChange = { onPriorityTypeChange(ExperiencePriorityType.VITALITY_POTION) },
                modifier = Modifier.weight(1f)
            )
        }
        
        // DIY玩法 - 单独一行
        CheckboxOptionRow(
            title = "DIY玩法",
            checked = priorityType == ExperiencePriorityType.CUSTOM_ORDER,
            onCheckedChange = { onPriorityTypeChange(ExperiencePriorityType.CUSTOM_ORDER) }
        )
        
        // 自定义顺序选择区域
        if (priorityType == ExperiencePriorityType.CUSTOM_ORDER) {
            CustomOrderSelectionArea(
                customOrder = customOrder,
                onCustomOrderChange = onCustomOrderChange
            )
        }
    }
}

/**
 * 自定义顺序选择区域
 */
@Composable
private fun CustomOrderSelectionArea(
    customOrder: List<Int>,
    onCustomOrderChange: (List<Int>) -> Unit
) {
    var showCustomOrderDialog by remember { mutableStateOf(false) }
    
    // 选择区域 - 使用通用组件
    SelectionRow(
        label = "选择副本：",
        selectedText = if (customOrder.isEmpty()) "未选择" else "已选择${customOrder.size}个地图",
        onClick = { showCustomOrderDialog = true }
    )
    
    // 自定义顺序选择对话框
    if (showCustomOrderDialog) {
        val mapOptions = MistyMapping.getAllIdNameFormats()
        val selectedMapNames = customOrder.mapNotNull { mapId ->
            MistyMapping.getNameById(mapId)?.let { name -> "$mapId-$name" }
        }
        
        MultiSelectHashtagBottomSheet(
            title = "选择历练地图",
            initialTags = selectedMapNames,
            placeholder = "输入地图名称，回车添加",
            recommendedTags = mapOptions,
            onCancel = { showCustomOrderDialog = false },
            onComplete = { selectedItems ->
                val selectedIds = selectedItems.mapNotNull { item ->
                    val parts = item.split("-", limit = 2)
                    parts[0].toIntOrNull()
                }
                onCustomOrderChange(selectedIds)
                showCustomOrderDialog = false
            },
            onDismiss = { showCustomOrderDialog = false }
        )
    }
}